<template>
  <div class="container">
    <el-card shadow="never">
      <template #header>
        <div style="display:flex;align-items:center;gap:12px;">
          <span>编辑文章</span>
          <el-tag type="info">{{ slug }}</el-tag>
          <div style="flex:1;"></div>
          <el-button @click="$router.back()">返回</el-button>
          <el-button type="primary" :loading="saving" @click="save">保存</el-button>
        </div>
      </template>

      <el-form :model="form" label-width="84px">
        <el-form-item label="标题">
          <el-input v-model="form.title" placeholder="输入标题" />
        </el-form-item>
        <el-form-item label="摘要">
          <el-input type="textarea" v-model="form.summary" :rows="3" placeholder="简要描述" />
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker v-model="form.date" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="form.tags" multiple filterable allow-create default-first-option placeholder="输入或选择标签">
            <el-option v-for="t in allTags" :key="t" :label="t" :value="t" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容(HTML)">
          <el-input type="textarea" v-model="form.content" :rows="10" placeholder="可直接写 HTML 片段" />
        </el-form-item>
        <el-form-item label="统计">
          <el-space wrap>
            <el-tag type="info">字数：{{ wordCount }}</el-tag>
            <el-tag type="success">标题：{{ titleCount }}</el-tag>
          </el-space>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never" style="margin-top:16px;">
      <template #header>
        <strong>实时预览</strong>
      </template>
      <div v-html="form.content || '<p class=\'muted\'>暂无内容</p>'"></div>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { fetchPostBySlug, fetchAllTags, savePost } from '@/services/blogService'

const route = useRoute()
const slug = route.params.slug
const form = reactive({ title: '', summary: '', date: '', tags: [], content: '' })
const saving = ref(false)
const allTags = ref([])

onMounted(async () => {
  const post = await fetchPostBySlug(slug)
  if (post) Object.assign(form, post)
  allTags.value = await fetchAllTags()
})

async function save() {
  saving.value = true
  await savePost({ ...form, slug })
  saving.value = false
  ElMessage.success('已保存（前端本地模拟）')
}

const wordCount = computed(() => (form.content || '').replace(/<[^>]*>/g, '').trim().length)
const titleCount = computed(() => (form.title || '').trim().length)
</script>


